#!/bin/bash

set -e

SKIP_MERGE=0

if [ $# == 1 ] ; then
    if [ "$1" == "skipMerge" ] ; then
        SKIP_MERGE=1
    fi
fi

cd ./web

echo Building web source...
pnpm run build
wait
if [ $? -ne 0 ]; then
    exit $?
fi

echo Deleting server static file...
rm -rf ../server/src/main/resources/static/*

echo Copying web static file to server resources directory...
cp -R dist/* ../server/src/main/resources/static/

cd ../server

./gradlew clean
wait
if [ $? -ne 0 ]; then
    exit $?
fi

BUILD_SERVER_CMD="./gradlew jar"
if [ $SKIP_MERGE -eq 1 ]; then
    BUILD_SERVER_CMD="./gradlew jar -PskipMerge=1"
fi

echo Building server source: $BUILD_SERVER_CMD
$BUILD_SERVER_CMD
wait
if [ $? -ne 0 ]; then
    exit $?
fi

cd ../

if [ ! -d "bin" ]; then
    mkdir bin
else
    rm -rf bin/*
fi

if [ $SKIP_MERGE -eq 1 ]; then
    cp -R ./server/build/libs/* ./bin/
else
    cp ./server/build/libs/etcd-workbench.jar ./bin/
fi